/*
 * Copyright 2016, The Android Open Source Project
 * Copyright (c) 2017-2018 Spotify AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.ohos.architecture.blueprints.todoapp.taskdetail.view;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import com.example.ohos.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent;
import com.ohos.mobius.ResourceTable;
import com.spotify.mobius.Connectable;
import com.spotify.mobius.Connection;
import com.spotify.mobius.functions.Consumer;

import javax.annotation.Nonnull;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

import static com.example.ohos.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent.activateTaskRequested;
import static com.example.ohos.architecture.blueprints.todoapp.taskdetail.domain.TaskDetailEvent.completeTaskRequested;

/**
 * TaskDetailViews
 */
public class TaskDetailViews implements TaskDetailViewActions, Connectable<TaskDetailViewData, TaskDetailEvent> {
    private final Observable<TaskDetailEvent> mMenuEvents;
    private Text mDetailTitle;
    private Button mEditButton;
    private Text mDetailDescription;
    private Checkbox mDetailCompleteStatus;
    private Context context;

    public TaskDetailViews(Context context, AbilitySlice abilitySlice, Observable<TaskDetailEvent> menuEvents) {
        this.context = context;
        mMenuEvents = menuEvents;
        mDetailTitle = (Text) abilitySlice.findComponentById(ResourceTable.Id_task_detail_title);
        mDetailDescription = (Text) abilitySlice.findComponentById(ResourceTable.Id_task_detail_description);
        mDetailCompleteStatus = (Checkbox) abilitySlice.findComponentById(ResourceTable.Id_task_detail_complete);
        mEditButton = (Button) abilitySlice.findComponentById(ResourceTable.Id_bt_edit);
    }

    @Override
    public void showTaskMarkedComplete() {
        showMessage(ResourceTable.String_task_marked_complete);
    }

    @Override
    public void showTaskMarkedActive() {
        showMessage(ResourceTable.String_task_marked_active);
    }

    @Override
    public void showTaskDeletionFailed() {
        showMessage("Failed to delete task");
    }

    @Override
    public void showTaskSavingFailed() {
        showMessage("Failed to save change");
    }

    private void showMessage(int messageRes) {
        showMessage(context.getString(messageRes));
    }

    private void showMessage(String messageRes) {
        DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(context)
            .parse(ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
        text.setText(messageRes);

        ToastDialog toast = new ToastDialog(context);
        toast.setContentCustomComponent(toastLayout);
        toast.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        toast.setAlignment(LayoutAlignment.BOTTOM);
        toast.show();
    }

    private void render(TaskDetailViewData viewData) {
        mDetailCompleteStatus.setChecked(viewData.completedChecked());
        bindTextViewData(mDetailTitle, viewData.title());
        bindTextViewData(mDetailDescription, viewData.description());
    }

    private void bindTextViewData(Text textView, TaskDetailViewData.TextViewData viewData) {
        textView.setVisibility(viewData.visibility());
        textView.setText(viewData.text());
    }

    @Nonnull
    @Override
    public Connection<TaskDetailViewData> connect(Consumer<TaskDetailEvent> output) {
        mEditButton.setClickedListener(__ -> {
            output.accept(TaskDetailEvent.editTaskRequested());
        });

        mDetailCompleteStatus.setCheckedStateChangedListener(
            (buttonView, isChecked) -> {
                if (isChecked) {
                    output.accept(completeTaskRequested());
                } else {
                    output.accept(activateTaskRequested());
                }
            });

        Disposable disposable = mMenuEvents.retry().subscribe(output::accept,
            tt -> HiLog.debug(new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG"), "Menu events seem to fail"));

        return new Connection<TaskDetailViewData>() {
            @Override
            public void accept(TaskDetailViewData value) {
                render(value);
            }

            @Override
            public void dispose() {
                disposable.dispose();
                mDetailCompleteStatus.setCheckedStateChangedListener(null);
            }
        };
    }
}
